package com.learnyou.server.xingzuo.controller.app.impl;

import com.learnyou.server.xingzuo.biz.common.WechatClientBiz;
import com.learnyou.server.xingzuo.biz.handle.TokenContextUtil;
import com.learnyou.server.xingzuo.common.config.WechatThirdConfig;
import com.learnyou.server.xingzuo.controller.app.WechatThirdEventApiResource;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
public class WechatThirdEventApiController implements WechatThirdEventApiResource {

    @Resource
    private WechatClientBiz wechatClientBiz;

    @Resource
    private WechatThirdConfig wechatThirdConfig;

    @Override
    public String getAuthUrl() {
        // 预授权码
        String preAuthCode = wechatClientBiz.getPreAuthCode();
        log.info("preAuthCode", preAuthCode);

        // 回调地址
        String redirectUrl = this.getCallbackUrlWithOrgID();

        String url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=%s&pre_auth_code=%s&redirect_uri=%s&auth_type=%s";

        String authURL = String.format(url, wechatThirdConfig.getAppId(), preAuthCode, redirectUrl, "1");
        log.info("callbackUrl: {}", authURL);
        return authURL;
    }

    private String getCallbackUrlWithOrgID() {
        try {
            String redirectUrl = wechatThirdConfig.getCallback();
            // 回调地址增加 机构ID
            Integer orgId = TokenContextUtil.getUserInfo().getOrgId();
            URIBuilder redirectUrlBuilder = new URIBuilder(redirectUrl);
            redirectUrlBuilder.addParameter("orgId", orgId.toString());
            redirectUrl = redirectUrlBuilder.toString();
            log.info("redirectUrl: {}", redirectUrl);
            redirectUrl = URLEncoder.encode(redirectUrl, StandardCharsets.UTF_8.toString());
            return redirectUrl;
        } catch (Exception ex) {
            log.error("error: ", ex);
            return null;
        }
    }
}
